package com.link.play.fit.ai.utils

import android.content.Context
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequest
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import com.link.play.fit.ai.GlobalConfig.NOTIFICATION_DRINKING_REMINDER
import com.link.play.fit.ai.GlobalConfig.NOTIFICATION_WEEKLY_MONDAY
import com.link.play.fit.ai.GlobalConfig.NO_VIP_NOTIFICATION_NAME
import com.link.play.fit.ai.kv.AuthCache.isVip
import com.link.play.fit.ai.pushWorker.DrinkSchedulerWorker
import com.link.play.fit.ai.pushWorker.PushNotificationWorker
import com.link.play.fit.ai.pushWorker.WeeklyPushWorker
import com.link.play.fit.ai.utils.WeekDatesUtil.getNextMondayDelay
import java.util.Calendar
import java.util.concurrent.TimeUnit


object NotifycationUtils {

    // 推送间隔配置（单位：小时）
    val intervals = listOf(6, 24, 48, 72, 96, 144, 168)

    // 启动推送 未订阅的用户
     fun startPeriodicPushes(context: Context, nextCount: Int) {
        if(isVip){
            WorkManager.getInstance(context).cancelUniqueWork(NO_VIP_NOTIFICATION_NAME)
        }else{
            val delayHours = intervals[nextCount]
            val delayMillis = delayHours * 60 * 60 * 1000L

            val workRequest = OneTimeWorkRequestBuilder<PushNotificationWorker>()
                .setInitialDelay(delayMillis, TimeUnit.MILLISECONDS)
                .build()
            WorkManager.getInstance(context)
                .enqueueUniqueWork(
                    NO_VIP_NOTIFICATION_NAME,
                    ExistingWorkPolicy.KEEP,
                    workRequest
                )
        }
    }



    /**
     * 每周一 体重推送
     */
    fun scheduleWeeklyPush(context: Context) {
        if(isVip){
            val delay = getNextMondayDelay()
            val workRequest = OneTimeWorkRequestBuilder<WeeklyPushWorker>()
                .setInitialDelay(delay, TimeUnit.MILLISECONDS)
                .build()

            WorkManager.getInstance(context).enqueueUniqueWork(
                NOTIFICATION_WEEKLY_MONDAY,
                ExistingWorkPolicy.KEEP,
                workRequest
            )
        }else{
            WorkManager.getInstance(context).cancelUniqueWork(NOTIFICATION_WEEKLY_MONDAY)
        }
    }

    /**
     * 饮水提醒
     */
    fun scheduleDrinkingReminders(context: Context) {
        if(isVip){
            val workManager = WorkManager.getInstance(context)
            // 每天午夜触发 DailySchedulerWorker
            val dailyWorkRequest = PeriodicWorkRequestBuilder<DrinkSchedulerWorker>(1, TimeUnit.DAYS)
                .setInitialDelay(initialDelayToNextMidnight(), TimeUnit.MILLISECONDS)
                .build()

            workManager.enqueueUniquePeriodicWork(
                NOTIFICATION_DRINKING_REMINDER,
                ExistingPeriodicWorkPolicy.REPLACE,
                dailyWorkRequest
            )
            // 立即执行一次以安排当天的任务
            workManager.enqueue(OneTimeWorkRequest.from(DrinkSchedulerWorker::class.java))
        }else{
            WorkManager.getInstance(context).cancelUniqueWork(NOTIFICATION_DRINKING_REMINDER)
        }

    }

    private fun initialDelayToNextMidnight(): Long {
        val calendar = Calendar.getInstance().apply {
            add(Calendar.DAY_OF_MONTH, 1)
            set(Calendar.HOUR_OF_DAY, 0)
            set(Calendar.MINUTE, 0)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)
        }
        return calendar.timeInMillis - System.currentTimeMillis()
    }

}